"""
日志管理模块

作者：修炼者 (7457222@qq.com)
日期：2024-12-10

用法：
    from jygt_coder_loger import get_logger
    logger = get_logger('my_logger', use_rotating=True, use_timed=False)
    logger.debug('This is a debug message.')
"""
import logging
import os
from logging.handlers import RotatingFileHandler, TimedRotatingFileHandler
from typing import Optional

# 缓存已创建的日志记录器
_logger_cache = {}

def find_project_root(start_dir: str) -> str:
    """从 start_dir 开始向上查找项目根目录。"""
    current_dir = start_dir
    while True:
        if os.path.exists(os.path.join(current_dir, 'src')):
            return current_dir
        parent_dir = os.path.dirname(current_dir)
        if parent_dir == current_dir:
            raise FileNotFoundError("Project root not found.")
        current_dir = parent_dir

def create_log_directory(log_file_path: str) -> None:
    """如果日志目录不存在，则创建日志目录。"""
    os.makedirs(os.path.dirname(log_file_path), exist_ok=True)

def configure_rotating_handler(log_file_path: str, max_bytes: int, backup_count: int) -> RotatingFileHandler:
    """配置并返回一个 RotatingFileHandler。"""
    handler = RotatingFileHandler(log_file_path, maxBytes=max_bytes, backupCount=backup_count)
    formatter = logging.Formatter('%(process)d - %(thread)d - %(levelname)s - %(asctime)s - %(name)s - %(filename)s - %(lineno)d - %(message)s')
    handler.setFormatter(formatter)
    return handler

def configure_timed_handler(log_file_path: str) -> TimedRotatingFileHandler:
    """配置并返回一个 TimedRotatingFileHandler。"""
    handler = TimedRotatingFileHandler(log_file_path, when='midnight', interval=1, backupCount=7)
    formatter = logging.Formatter('%(process)d - %(thread)d - %(levelname)s - %(asctime)s - %(name)s - %(filename)s - %(lineno)d - %(message)s')
    handler.setFormatter(formatter)
    return handler

def setup_logging(project_root: str, log_file_path: str = 'log/jygt_coder.log', max_bytes: int = 10 * 1024 * 1024, backup_count: int = 5,
                 use_rotating: bool = True, use_timed: bool = False) -> logging.Logger:
    """设置日志记录，并使用指定的处理器。"""
    absolute_log_path = os.path.join(project_root, log_file_path)
    create_log_directory(absolute_log_path)

    logger = logging.getLogger(log_file_path)
    logger.setLevel(logging.DEBUG)

    # 检查是否已经添加了处理器
    if use_rotating and not any(isinstance(h, RotatingFileHandler) for h in logger.handlers):
        rotating_handler = configure_rotating_handler(absolute_log_path, max_bytes, backup_count)
        logger.addHandler(rotating_handler)

    if use_timed and not any(isinstance(h, TimedRotatingFileHandler) for h in logger.handlers):
        timed_handler = configure_timed_handler(absolute_log_path)
        logger.addHandler(timed_handler)

    return logger

def get_logger(name: str, use_rotating: bool = True, use_timed: bool = False) -> logging.Logger:
    """获取指定名称和配置的日志记录器。"""
    if name in _logger_cache:
        return _logger_cache[name]

    project_root = find_project_root(os.path.abspath(__file__))
    logger = setup_logging(project_root, use_rotating=use_rotating, use_timed=use_timed)
    logger.name = name  # 设置日志记录器的名称

    _logger_cache[name] = logger
    return logger